const CustomExceptions = require('../exception/index');

const errorHandle = async (ctx, next) => {
  try {
    console.log('进入错误捕捉中间件');
    await next();
    console.log('退出错误捕捉中间件');
  } catch (err) {
    let status = err.code || 500;
    let error = {
      status,
    };
    if (err instanceof CustomExceptions) {
      error = err;
    } else {
      error.msg = err.message || err;
    }
    ctx.output.body = error;
    ctx.app.emit('error', ctx.output.body);
  }
}

module.exports = errorHandle;